package com.example.tool.conf;

import com.example.tool.bean.business.WarehouseInterceptionConfig;
import com.example.tool.erp.sdk.api.sales.dto.TradeQueryResponse;
import com.example.tool.service.RedisService;
import com.example.tool.util.DateUtil;
import com.example.tool.util.ExpressDeliveryUtil.ExpressDeliveryResult;
import com.example.tool.util.ExpressDeliveryUtil.ExpressDeliveryTrack;
import com.example.tool.util.ExpressDeliveryUtil.ExpressDeliveryUtil;
import com.example.tool.util.WDTUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.example.tool.conf.WarehouseMsgConfig.FORMATTER_YYYY_MM;
import static com.example.tool.conf.WarehouseMsgConfig.WAREHOUSE_COLLECTION_DELAY_CONFIG;
import static com.example.tool.conf.WarehouseMsgConfig.WAREHOUSE_LOGISTICS_ABNORMALITY_CONFIG;
import static com.example.tool.conf.WarehouseMsgConfig.WAREHOUSE_WITHOUT_HAIR_CONFIG;
import static com.example.tool.conf.WarehouseMsgConfig.collectionDelayEndingContent;
import static com.example.tool.conf.WarehouseMsgConfig.collectionDelayHeaderValues;
import static com.example.tool.conf.WarehouseMsgConfig.collectionDelayKeyTemplate;
import static com.example.tool.conf.WarehouseMsgConfig.collectionDelayMsgTemplate;
import static com.example.tool.conf.WarehouseMsgConfig.collectionDelayMsgTitle;
import static com.example.tool.conf.WarehouseMsgConfig.frozenWarehouseNos;
import static com.example.tool.conf.WarehouseMsgConfig.logisticsAbnormalityEndingContent;
import static com.example.tool.conf.WarehouseMsgConfig.logisticsAbnormalityHeaderValues;
import static com.example.tool.conf.WarehouseMsgConfig.logisticsAbnormalityMsgTemplate;
import static com.example.tool.conf.WarehouseMsgConfig.logisticsAbnormalityMsgTitle;
import static com.example.tool.conf.WarehouseMsgConfig.transferTimeoutAfterKeyTemplate;
import static com.example.tool.conf.WarehouseMsgConfig.transferTimeoutKeyTemplate;
import static com.example.tool.conf.WarehouseMsgConfig.updateBatchSize;
import static com.example.tool.conf.WarehouseMsgConfig.withoutHairEndingContent;
import static com.example.tool.conf.WarehouseMsgConfig.withoutHairHeaderValues;
import static com.example.tool.conf.WarehouseMsgConfig.withoutHairMsgTemplate;
import static com.example.tool.conf.WarehouseMsgConfig.withoutHairMsgTitle;
import static com.example.tool.service.AsyncService.findPrefix;
import static com.example.tool.util.DateUtil.findTimeDifference;

@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    @Autowired
    private RedisService redisService;
    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * Redis失效事件 key
     *
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String key = message.toString();
        System.out.println("onMessage:"+key);
        if(StringUtils.isBlank(key)){
            return;
        }
        List<String>prefixs=Arrays.asList(collectionDelayKeyTemplate.substring(0, collectionDelayKeyTemplate.lastIndexOf(":")),
        transferTimeoutKeyTemplate.substring(0, transferTimeoutKeyTemplate.lastIndexOf(":")),
        transferTimeoutAfterKeyTemplate.substring(0, transferTimeoutAfterKeyTemplate.lastIndexOf(":")));
        if(!prefixs.contains(key)){
            return;
        }
        String sheetId= LocalDateTime.now().format(FORMATTER_YYYY_MM);
        String prefix = findPrefix(key);
        String logisticsNo=key.replace(prefix, "");
            ExpressDeliveryResult result = ExpressDeliveryUtil.queryLogistics(logisticsNo);
            List<ExpressDeliveryTrack> tracks = result.getTracks();
            String lType=result.getType();
            Date scanDateT=null;
            if(!tracks.isEmpty()){
                scanDateT=tracks.get(tracks.size()-1).getScanDate();

                Long timeDifference = findTimeDifference(scanDateT, new Date());
                if(timeDifference<86400){
                    return;
                }
            }
            TradeQueryResponse.OrderItem orderItem = WDTUtil.logisticsNoQueryOrder(logisticsNo);
            String warehouseNo = orderItem.getWarehouseNo();
            List<List<String>>values=new ArrayList<>();
            String workbookId="";
            String secret="";
            String token="";
            List<String> atMobiles = null;
            List<String> atUserIds = null;
            switch (prefix){
                case "sys:collectionDelayKey":
                  values=Collections.singletonList(Arrays.asList(orderItem.getSrcTids(), orderItem.getStockoutNo(), orderItem.getTradeNo(), orderItem.getLogisticsNo(), DateUtil.toDateToStr(orderItem.getConsignTime())));
                  WarehouseInterceptionConfig collectionDelayConfig = WAREHOUSE_COLLECTION_DELAY_CONFIG.get(warehouseNo);
                  workbookId = collectionDelayConfig.getWorkbookId();
                  secret = collectionDelayConfig.getSecret();
                  token = collectionDelayConfig.getToken();
                  atMobiles = collectionDelayConfig.getAtMobiles();
                  atUserIds = collectionDelayConfig.getAtUserIds();
//                    updateAiExcelSendMsg(1,workbookId,secret,token,atMobiles,atUserIds,values,sheetId,collectionDelayHeaderValues,collectionDelayMsgTitle,collectionDelayMsgTemplate,collectionDelayEndingContent,collectionDelayRangeAddressTemplate,
//                  updateBatchSize,dataSaveDays,timeUnit,keyTemplate);
                    WarehouseMsgConfig.updateAiExcelSendMsg(1,workbookId,secret,token,atMobiles,atUserIds,values,sheetId,collectionDelayHeaderValues,collectionDelayMsgTitle,collectionDelayMsgTemplate,collectionDelayEndingContent,
                  updateBatchSize);
                break;//揽收超时
            case "sys:transferTimeout":
                 String scanDateStr="";
                 if(!tracks.isEmpty()){
                 scanDateStr=tracks.get(0).getScanDateStr();
                 }
                 values=Collections.singletonList(Arrays.asList(orderItem.getSrcTids(), orderItem.getStockoutNo(), orderItem.getTradeNo(), orderItem.getLogisticsNo(), scanDateStr));
                 WarehouseInterceptionConfig withoutHairConfig = WAREHOUSE_WITHOUT_HAIR_CONFIG.get(warehouseNo);
                 workbookId = withoutHairConfig.getWorkbookId();
                 secret = withoutHairConfig.getSecret();
                 token = withoutHairConfig.getToken();
                 atMobiles = withoutHairConfig.getAtMobiles();
                 atUserIds = withoutHairConfig.getAtUserIds();
               /* updateDocumentSending(1,workbookId,secret,token,atMobiles,atUserIds,values,sheetId,withoutHairHeaderValues,withoutHairMsgTitle,withoutHairMsgTemplate,withoutHairEndingContent,withoutHairRangeAddressTemplate,
                updateBatchSize,dataSaveDays,timeUnit,keyTemplate);*/
                WarehouseMsgConfig.updateAiExcelSendMsg(1,workbookId,secret,token,atMobiles,atUserIds,values,sheetId,withoutHairHeaderValues,withoutHairMsgTitle,withoutHairMsgTemplate,withoutHairEndingContent,
                updateBatchSize);
                break;//中转超时
            case "sys:transferTimeoutAfter":
                values=Collections.singletonList(Arrays.asList(orderItem.getSrcTids(), orderItem.getStockoutNo(), orderItem.getTradeNo(), orderItem.getLogisticsNo()));
                if(!frozenWarehouseNos.contains(warehouseNo)){
                    return;
                }
                WarehouseInterceptionConfig conf = WAREHOUSE_LOGISTICS_ABNORMALITY_CONFIG.get(warehouseNo).stream().collect(Collectors.toList()).get(0);
                workbookId = conf.getWorkbookId();
                secret = conf.getSecret();
                token = conf.getToken();
                atMobiles = conf.getAtMobiles();
                atUserIds = conf.getAtUserIds();
                /*updateDocumentSending(conf.getPlatform(),workbookId,secret,token,atMobiles,atUserIds,values,sheetId,logisticsAbnormalityHeaderValues,logisticsAbnormalityMsgTitle,logisticsAbnormalityMsgTemplate,logisticsAbnormalityEndingContent,logisticsAbnormalityRangeAddressTemplate,
                updateBatchSize,dataSaveDays,timeUnit,keyTemplate); */
                WarehouseMsgConfig.updateAiExcelSendMsg(1,workbookId,secret,token,atMobiles,atUserIds,values,sheetId,logisticsAbnormalityHeaderValues,logisticsAbnormalityMsgTitle,logisticsAbnormalityMsgTemplate,logisticsAbnormalityEndingContent,
                updateBatchSize);
                break;//中转后物流异常
        }
    }



}

